/**
 * 
 */
package ch.baeni.jee.web;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import ch.baeni.jee.model.User;
import ch.baeni.jee.service.UserService;
import ch.baeni.jee.util.SLL_Globals.LoginStatus;

/**
 * @author Benjamin
 *
 */
@ManagedBean(name="loginBean")
@SessionScoped
public class LoginBean extends AbstractBean {
	private String username;
	private String password;

	@Inject
	private UserService userService;
	
	@Inject
	private FacesContext facesContext;
	
	private User user;

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	/*
	public UserService getUserService() {
		if (userService == null) {
			 userService = new UserService();
		}
		return userService;
	}
	*/
	/**
	 * Führt das Login für einen User aus
	 * @return String für Navigation
	 */
	public String doLogin() {
//		log.debug(" doLogin "+ username);

//		userService = getUserService();
		user = userService.doLogin(username, password);
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
		session.setAttribute("loginBean", this);
		
		if (user != null) {

//			log.debug(" user status "+ user.getLoginStatus());

			if (LoginStatus.INVALID_USERNAME_OR_PASSWORD == user.getLoginStatus()) {
				user = null;
				FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "login_invalid_user_or_password", "Error");
				facesContext.addMessage(null, m);
				//displayErrorMessage("login_invalid_user_or_password");
				return "login";

			} else if (LoginStatus.INACTIVE == user.getLoginStatus()) {
				user = null;
				FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "login_user_inactiv", "Error");
				facesContext.addMessage(null, m);
				//displayErrorMessage("login_user_inactiv");
				return "login";

			} else if (LoginStatus.SUCCESSFUL == user.getLoginStatus()) {
				FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_INFO, "login_successful", "Success");
				facesContext.addMessage(null, m);
//				displayInfoMessage("login_successful");
				return "welcome";
			}

		}

		displayErrorMessage("login_invalid_user_or_password");
		return "login";
	}
	/**
	 * Führt das Logout durch
	 * @return String für die Navigation
	 */
	public String doLogout(){
		user = null;
		return ("login");
	}
	public boolean isLoggedIn(){
		return user!=null;
	}

	public User getCurrentUser(){
		return user;
	}
}
